const innerAudioContext = uni.createInnerAudioContext() //想要实现暂停功能就要把该对象变为全局属性
class websocketUtil {
	constructor(url, infoData, time) {
		this.is_open_socket = false //避免重复连接
		this.url = url //地址
		this.data = null
		this.infoData = infoData
		//心跳检测
		this.timeout = time //多少秒执行检测
		this.heartbeatInterval = null //检测服务器端是否还活着
		this.reconnectTimeOut = null //重连之后多久再次重连

		try {
			return this.connectSocketInit()
		} catch (e) {
			this.is_open_socket = false
			this.reconnect();
		}
	}
	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit() {
		this.socketTask = uni.connectSocket({
			url: this.url,
			success: () => {
				// 返回实例
				return this.socketTask
			},
		});
		this.socketTask.onOpen((res) => {
			clearTimeout(this.reconnectTimeOut)
			clearTimeout(this.heartbeatInterval)
			this.is_open_socket = true;
			this.start();
			// 注：只有连接正常打开中 ，才能正常收到消息
			this.socketTask.onMessage((res) => {
				let data = JSON.parse(res.data)
				if (data.code == 0) {
					if (data.type == 'normal') {
						innerAudioContext.loop = false; //循环播放
						innerAudioContext.src =
							"https://peiyin.wozhiyi.com/download?url=https://img03.wozhiyi.com/peiyin/tmp/20231220/98cb91cebebdc97a962a908d0511a76e.wav";
						innerAudioContext.play()
						uni.showModal({
							title: "呼叫处理",
							content: "您有个新的机修消息，请查看",
							success: function(res) {
								innerAudioContext.stop()
								if (res.confirm) {
									uni.navigateTo({
										url: "/pages/HomePage/CallDeal/index"
									})
								} else if (res.cancel) {
									uni.$emit('onCallMessage')
								}
							}
						})
					}
				}
			});
		})
		// 监听连接失败，这里代码我注释掉的原因是因为如果服务器关闭后，和下面的onclose方法一起发起重连操作，这样会导致重复连接
		uni.onSocketError((res) => {
			this.is_open_socket = false;
			this.reconnect();
		});
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onClose(() => {
			this.is_open_socket = false;
			// this.reconnect();
		})
	}
	//发送消息
	send(value) {
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		var that = this
		this.socketTask.send({
			data: value,
			async success() {
				clearInterval(that.heartbeatInterval)
				that.start()
			},
		});
	}
	//开启心跳检测
	start() {
		this.heartbeatInterval = setInterval(() => {
			this.send(JSON.stringify(this.infoData));
		}, this.timeout)
	}
	//重新连接
	reconnect() {
		//停止发送心跳
		clearInterval(this.heartbeatInterval)
		//如果不是人为关闭的话，进行重连
		if (!this.is_open_socket) {
			this.reconnectTimeOut = setTimeout(() => {
				this.connectSocketInit();
			}, 3000)
		}
	}
	//外部获取消息
	getMessage(callback) {
		this.socketTask.onMessage((res) => {
			return callback(res)
		})
	}
	//手动关闭
	close() {
		this.is_open_socket = false;
		this.socketTask.close()
	}
}

module.exports = websocketUtil